<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能聊天助手</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- 引入Font Awesome库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #66bb6a 0%, #ffffff 100%);
            font-family: Arial, sans-serif;
            min-height: 100vh;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
        }

        #loading {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .loader {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #66bb6a;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        #app {
            display: none;
        }

        .chat-container {
            position: relative;
            max-width: 800px;
            width: 90%;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            height: 90vh;
            display: flex;
            flex-direction: column;
            background-image: url('https://image.baidu.com/front/aigc?atn=aigc&fr=home&imgcontent=%7B%22aigcQuery%22%3A%22%22%2C%22imageAigcId%22%3A%224199096378%22%7D&isImmersive=1&pd=image_content&quality=1&ratio=1%3A1&sa=searchpromo_shijian_photohp_inspire&tn=aigc&top=%7B%22sfhs%22%3A1%7D&word=%E8%87%AA%E7%84%B6%E9%A3%8E%E5%85%89%EF%BC%8C%E9%9B%AA%E5%B1%B1%EF%BC%8C%E6%B2%B3%E6%B5%81%E7%80%91%E5%B8%83%EF%BC%8C%E8%A6%86%E7%9B%96%E9%9B%AA%E7%9A%84%E5%B1%B1%E5%B3%B0%EF%BC%8C%E8%93%9D%E5%A4%A9%E7%99%BD%E4%BA%91%EF%BC%8C4K%E8%B6%85%E6%B8%85%EF%BC%8C%E7%9C%9F%E5%AE%9E%E4%B8%BB%E4%B9%89%EF%BC%8C%E5%86%B7%E9%9D%99%EF%BC%8C%E9%98%B3%E5%85%89%EF%BC%8C%E5%86%B7%E5%B3%BB%E5%88%9A%E7%A1%AC');
            background-size: cover;
            background-position: center;
            background-blend-mode: overlay;
            background-color: rgba(255, 255, 255, 0.8);
        }

        .new-chat-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: #D32F2F;
            color: white;
            border: none;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .new-chat-btn:hover {
            background-color: #B71C1C;
        }

        .chat-header {
            text-align: center;
            padding: 20px;
            border-bottom: 1px solid #ebeef5;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
        }

        .message {
            max-width: 70%;
            margin-bottom: 15px;
            display: flex;
            align-items: flex-end;
        }

        .message.user {
            justify-content: flex-end;
            margin-left: auto;
            align-items: flex-end;
        }

        .message.assistant {
            justify-content: flex-start;
            margin-right: auto;
            align-items: flex-start;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #66bb6a;
            color: white;
            flex-shrink: 0;
        }

        .message.user .message-avatar {
            margin-left: 10px;
            margin-right: 0;
            background-color: #D32F2F;
            color: white;
        }

        .message-content {
            padding: 12px 16px;
            border-radius: 8px;
            position: relative;
            background-color: #f0f2f5;
            color: #303133;
        }

        .message.user .message-content {
            background-color: #D32F2F;
            color: white;
            border-radius: 8px 8px 0 8px;
            margin-right: 0;
            align-self: flex-end;
        }

        .message.assistant .message-content {
            background-color: #66bb6a;
            color: white;
            border-radius: 8px 8px 8px 0;
            align-self: flex-start;
        }

        .typing-indicator {
            display: inline-block;
            padding: 12px 16px;
            background-color: #f0f2f5;
            border-radius: 8px;
            color: #909399;
        }

        .chat-input-area {
            padding: 20px;
            border-top: 1px solid #ebeef5;
            background-color: #fff;
        }

        .chat-input {
            display: flex;
            gap: 10px;
        }

        .el-button--primary {
            background-color: #D32F2F;
            border-color: #D32F2F;
        }

        .el-button--primary:hover {
            background-color: #B71C1C;
            border-color: #B71C1C;
        }

        .heart-icon {
            color: red;
            margin-right: 5px;
        }
    </style>
</head>

<body>
    <div id="loading">
        <div class="loader"></div>
    </div>
    <div id="app" class="chat-container">
        <button class="new-chat-btn" @click="startNewChat">
            <i class="fas fa-plus"></i>
        </button>
        <div class="chat-header">
            <h2>智能聊天助手</h2>
        </div>
        <div class="chat-messages">
            <div v-for="(message, index) in messages" :key="index" class="message" :class="message.role">
                <div v-if="message.role === 'assistant'" class="message-avatar">
                    <i class="fas fa-robot"></i>
                </div>
                <div class="message-content">
                    <span v-if="message.role === 'user'"
                        v-html="message.content.replace(/\n/g, '<br/>&#10084; ')"></span>
                    <span v-else v-html="message.content"></span>
                </div>
                <div v-if="message.role === 'user'" class="message-avatar">
                    <i class="fas fa-user"></i>
                </div>
            </div>
            <div v-if="isTyping" class="message assistant">
                <div class="typing-indicator">
                    <span>正在输入...</span>
                </div>
            </div>
        </div>
        <div class="chat-input-area">
            <div class="chat-input">
                <el-input v-model="newMessage" placeholder="请输入消息" @keyup.enter.native="sendMessage"
                    :disabled="isLoading"></el-input>
                <el-button type="primary" @click="sendMessage" :loading="isLoading">发送</el-button>
            </div>
        </div>
    </div>

    <script>
        // Show main content when page is fully loaded
        window.addEventListener('load', () => {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('app').style.display = 'flex';
        });

        new Vue({
            el: '#app',
            data: {
                messages: [],
                newMessage: '',
                isLoading: false,
                isTyping: false,
                eventSource: null,
                sessionId: null,
                userName: (function () {
                    const urlParams = new URLSearchParams(window.location.search);
                    return decodeURIComponent(urlParams.get('username') || '');
                })()
            },
            mounted() {
                this.checkUsername();
                // this.startNewChat();
            },
            methods: {
                /**
                * 新增钩子函数，当页面刚加载的时候，判断username是否为空，如果为空，就去到index.html
                */
                async checkUsername() {
                    debugger
                    if (!this.userName) {
                        this.$message.error('请登录');
                        window.location.href = '/index.html';
                    }
                },
                async startNewChat() {
                    if (this.sessionId) {
                        // 调用结束会话接口
                        fetch('/aigc/endSession', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                sessionId: this.sessionId
                            })
                        })
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error('Network response was not ok ' + response.statusText);
                                }
                            })
                            .catch(error => {
                                console.error('Fetch error:', error);
                                this.$message.error('结束会话出错，请重试');
                            });
                    }

                    this.messages = [];
                    this.newMessage = '';
                    this.isLoading = false;
                    this.isTyping = false;
                    if (this.eventSource) {
                        this.eventSource.close();
                    }
                    this.sessionId = null; // 重置 sessionId
                },

                sendMessage() {
                    if (this.newMessage.trim() === '' || this.isLoading) return;

                    this.isLoading = true;
                    this.isTyping = true;
                    this.messages.push({
                        role: 'user',
                        content: this.newMessage
                    });

                    // Clear current streaming message if exists
                    if (this.eventSource) {
                        this.eventSource.close();
                    }

                    // Create new streaming connection using fetch API
                    if (!this.sessionId) {
                        this.sessionId = crypto.randomUUID();
                    }
                    fetch('/aigc/chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            sessionId: this.sessionId,
                            questionContent: this.newMessage,
                            userName: this.userName
                        })
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok ' + response.statusText);
                            }
                            const reader = response.body.getReader();
                            const decoder = new TextDecoder('utf-8');
                            let done = false;

                            // Add assistant message placeholder
                            this.messages.push({
                                role: 'assistant',
                                content: ''
                            });
                            const assistantMessageIndex = this.messages.length - 1;

                            const readStream = () => {
                                return reader.read().then(({ done: doneReading, value }) => {
                                    done = doneReading;
                                    if (done) {
                                        this.isLoading = false;
                                        this.isTyping = false;
                                        // 添加滚动到最底部的逻辑
                                        this.$nextTick(() => {
                                            const chatMessages = document.querySelector('.chat-messages');
                                            chatMessages.scrollTop = chatMessages.scrollHeight;
                                        });
                                        return;
                                    }
                                    const chunk = decoder.decode(value, { stream: true });
                                    this.messages[assistantMessageIndex].content += chunk;
                                    console.log(chunk);

                                    // 添加滚动到最底部的逻辑
                                    this.$nextTick(() => {
                                        const chatMessages = document.querySelector('.chat-messages');
                                        chatMessages.scrollTop = chatMessages.scrollHeight;
                                    });

                                    return readStream();
                                });
                            }

                            readStream().catch(error => {
                                console.error('Fetch error:', error);
                                this.isLoading = false;
                                this.isTyping = false;
                                this.$message.error('连接出错，请重试');
                            });
                        })
                        .catch(error => {
                            console.error('Fetch error:', error);
                            this.isLoading = false;
                            this.isTyping = false;
                            this.$message.error('连接出错，请重试');
                        });

                    this.newMessage = '';
                }
            },
            beforeDestroy() {
                if (this.eventSource) {
                    this.eventSource.close();
                }
            }
        });
    </script>
</body>

</html>